package com.leetcode.math;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class intersection2 {

    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int num : nums1) {
            int count = map.getOrDefault(num, 0) + 1;
            map.put(num, count);
        }
        int[] intersection = new int[nums1.length];
        int index = 0;
        for (int num : nums2) {
            int count = map.getOrDefault(num, 0);
            if (count > 0) {
                intersection[index++] = num;
                count--;
                if (count > 0) {
                    map.put(num, count);
                } else {
                    map.remove(num);
                }
            }
        }
        return Arrays.copyOfRange(intersection, 0, index);
    }

    public int[] intersectPointer(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0, j = 0, m = nums1.length, n = nums2.length;
        int index = 0;
        int[] tmp = new int[Math.min(m,n)];
        while (i < m && j < n) {
            if (nums1[i] < nums2[j]) {
                i++;
            }else if (nums1[i] > nums2[j]) {
                j++;
            }else if (nums1[i] == nums2[j]) {
                tmp[index++] = nums1[i];
                i++;
                j++;
            }
        }
        return Arrays.copyOfRange(tmp,0,index);
    }


}
